<template>
  <ComponentContainerProperty v-model="formData.style">
    <template #default>
      <el-form :model="formData" label-width="80px" class="compact-form">
        <!-- 基本配置 -->
        <el-form-item class="section-header">
          <div class="section-title">基本配置</div>
        </el-form-item>
        <el-card shadow="never" class="config-card">
          <div class="config-section">
            <div class="section-label">位置设置</div>
            <el-form-item label="显示位置" prop="position" class="full-width-item">
              <el-radio-group v-model="formData.position" size="small">
                <el-radio value="left">左侧</el-radio>
                <el-radio value="right">右侧</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="距离顶部" prop="top" class="full-width-item">
              <el-input-number
                v-model="formData.top"
                :min="0"
                :max="1000"
                size="small"
                controls-position="right"
              />
              <span class="unit">px</span>
            </el-form-item>
          </div>
        </el-card>

        <!-- 侧边栏项目 -->
        <el-form-item class="section-header">
          <div class="section-title">侧边栏项目</div>
        </el-form-item>
        <el-card shadow="never" class="items-config-card">
          <div v-for="(item, index) in formData.items" :key="item.id" class="item-config">
            <div class="item-header">
              <span class="item-title">项目 {{ index + 1 }}</span>
              <div class="item-actions">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="removeItem(index)"
                  :disabled="formData.items.length <= 1"
                >
                  删除
                </el-button>
                <el-button 
                  v-if="index > 0"
                  type="primary" 
                  size="small" 
                  @click="moveItemUp(index)"
                >
                  上移
                </el-button>
                <el-button 
                  v-if="index < formData.items.length - 1"
                  type="primary" 
                  size="small" 
                  @click="moveItemDown(index)"
                >
                  下移
                </el-button>
              </div>
            </div>
            
            <div class="config-section">
              <div class="section-label">基本设置</div>
              <el-form-item label="是否启用" :prop="`items.${index}.enabled`" class="full-width-item">
                <el-switch v-model="formData.items[index].enabled" />
              </el-form-item>
            </div>
            
            <div class="config-section">
              <div class="section-label">图标配置</div>
              <el-form-item label="图标图片" :prop="`items.${index}.iconUrl`" class="full-width-item">
                <UploadImg 
                  v-model="formData.items[index].iconUrl"
                  :limit="1"
                >
                  <template #tip>建议尺寸 24x24px，支持PNG格式</template>
                </UploadImg>
              </el-form-item>
              <el-form-item label="背景颜色" :prop="`items.${index}.backgroundColor`" class="full-width-item">
                <el-color-picker 
                  v-model="formData.items[index].backgroundColor"
                  size="small"
                  show-alpha
                />
              </el-form-item>
            </div>
            
            <div class="config-section">
              <div class="section-label">弹框内容</div>
              <el-form-item label="弹框标题" :prop="`items.${index}.title`" class="full-width-item">
                <el-input
                  :model-value="formData.items[index].title"
                  @update:model-value="(value) => updateItemTitle(index, value)"
                  placeholder="请输入弹框标题"
                  maxlength="20"
                  size="small"
                />
              </el-form-item>
                     <el-form-item label="弹框内容" :prop="`items.${index}.content`" class="full-width-item">
                       <el-input
                         :model-value="formData.items[index].content"
                         @update:model-value="(value) => updateItemContent(index, value)"
                         type="textarea"
                         :rows="4"
                         placeholder="请输入弹框内容（支持换行）"
                         size="small"
                         resize="none"
                       />
                     </el-form-item>
            </div>
          </div>
          <div style="margin-top: 16px;">
            <el-button type="primary" size="small" @click="addItem">添加项目</el-button>
          </div>
        </el-card>
      </el-form>
    </template>
  </ComponentContainerProperty>
</template>

<script setup lang="ts">
import { SidebarProperty } from './config'
import { useVModel } from '@vueuse/core'
import { watch } from 'vue'

defineOptions({ name: 'SidebarProperty' })

const props = defineProps<{ modelValue: SidebarProperty }>()
const emit = defineEmits(['update:modelValue'])

const formData = useVModel(props, 'modelValue', emit)

// 添加调试信息，监控数据变化
console.log('🎯 侧边栏属性组件初始化')
console.log('   初始数据:', JSON.stringify(props.modelValue, null, 2))

// 监听formData变化，验证数据流是否正常
watch(
  () => formData.value,
  (newVal, oldVal) => {
    console.log('🔄 侧边栏数据变化 (useVModel自动同步):')
    if (newVal.items) {
      newVal.items.forEach((item, index) => {
        const oldContent = oldVal?.items?.[index]?.content || ''
        const newContent = item.content || ''
        if (oldContent !== newContent) {
          console.log(`   项目${index + 1} 内容变化:`)
          console.log(`     旧值: "${oldContent}" (${oldContent.length}字符)`)
          console.log(`     新值: "${newContent}" (${newContent.length}字符)`)
          
          // 检查是否有意外的数据重置
          if (newContent.length < oldContent.length && oldContent.length > 0) {
            console.warn(`⚠️ 警告：数据被截断！从 ${oldContent.length} 字符减少到 ${newContent.length} 字符`)
            console.warn(`   截断详情: "${oldContent}" -> "${newContent}"`)
          }
        }
      })
    }
  },
  { deep: true }
)

// 添加项目
const addItem = () => {
  const newId = Math.max(...formData.value.items.map(item => item.id), 0) + 1
  formData.value.items.push({
    id: newId,
    iconUrl: '',
    backgroundColor: '#409eff',
    title: '新项目',
    content: '请输入项目内容',
    enabled: true
  })
}

// 删除项目
const removeItem = (index: number) => {
  if (formData.value.items.length > 1) {
    formData.value.items.splice(index, 1)
  }
}

// 上移项目
const moveItemUp = (index: number) => {
  if (index > 0) {
    const items = formData.value.items
    const temp = items[index]
    items[index] = items[index - 1]
    items[index - 1] = temp
  }
}

// 下移项目
const moveItemDown = (index: number) => {
  if (index < formData.value.items.length - 1) {
    const items = formData.value.items
    const temp = items[index]
    items[index] = items[index + 1]
    items[index + 1] = temp
  }
}

// 明确更新项目标题的函数
const updateItemTitle = (index: number, value: string) => {
  if (formData.value.items[index]) {
    formData.value.items[index].title = value
  }
}

// 明确更新项目内容的函数，确保Vue能正确追踪变化
const updateItemContent = (index: number, value: string) => {
  console.log(`🔍 更新项目${index + 1}内容:`)
  console.log(`   新值: "${value}" (${value.length}字符)`)
  console.log(`   旧值: "${formData.value.items[index].content}" (${formData.value.items[index].content?.length || 0}字符)`)
  
  // 检查是否有数据被意外截断
  if (value.length < formData.value.items[index].content?.length) {
    console.warn(`⚠️ 警告：输入值比当前值短！可能被截断了`)
    console.warn(`   当前值: "${formData.value.items[index].content}" (${formData.value.items[index].content?.length}字符)`)
    console.warn(`   输入值: "${value}" (${value.length}字符)`)
  }
  
  // 使用Vue.set或直接赋值来确保响应式更新
  if (formData.value.items[index]) {
    formData.value.items[index].content = value
    console.log(`   更新后: "${formData.value.items[index].content}" (${formData.value.items[index].content?.length || 0}字符)`)
    
    // 强制触发响应式更新
    formData.value = { ...formData.value }
  }
}
</script>

<style scoped lang="scss">
// 全局表单项标签样式
:deep(.el-form-item__label) {
  color: #333 !important;
  font-weight: 500;
}

// 全局输入框文字样式
:deep(.el-input__inner) {
  color: #333 !important;
}

:deep(.el-input__inner::placeholder) {
  color: #999 !important;
}

// 单选按钮组文字样式
:deep(.el-radio__label) {
  color: #333 !important;
}

.compact-form {
  .el-form-item {
    margin-bottom: 12px;
    
    .el-form-item__label {
      color: #333 !important;
      font-weight: 500;
    }
  }
}

.section-header {
  margin-bottom: 8px !important;
  
  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    padding: 8px 0;
    border-bottom: 2px solid #409eff;
    margin-bottom: 8px;
  }
}

.config-card {
  margin-bottom: 12px;
  
  .config-section {
    margin-bottom: 16px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .section-label {
      font-size: 13px;
      font-weight: 600;
      color: #495057;
      margin-bottom: 8px;
      padding: 4px 0;
      border-left: 3px solid #409eff;
      padding-left: 8px;
      background: rgba(64, 158, 255, 0.05);
      border-radius: 0 4px 4px 0;
    }
  }
  
  .full-width-item {
    margin-bottom: 12px;
    
    .el-form-item__content {
      width: 100%;
    }
    
    .el-form-item__label {
      color: #333 !important;
      font-weight: 500;
    }
  }
}

.items-config-card {
  margin-bottom: 12px;
  
  .item-config {
    margin-bottom: 16px;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e9ecef;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .item-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      padding-bottom: 8px;
      border-bottom: 1px solid #dee2e6;
      
      .item-title {
        font-weight: bold;
        color: #333;
        font-size: 14px;
      }
      
      .item-actions {
        display: flex;
        gap: 6px;
        
        .el-button {
          padding: 4px 8px;
          font-size: 12px;
        }
      }
    }
  }
  
  .config-section {
    margin-bottom: 16px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .section-label {
      font-size: 13px;
      font-weight: 600;
      color: #495057;
      margin-bottom: 8px;
      padding: 4px 0;
      border-left: 3px solid #409eff;
      padding-left: 8px;
      background: rgba(64, 158, 255, 0.05);
      border-radius: 0 4px 4px 0;
    }
  }
  
  .full-width-item {
    margin-bottom: 12px;
    
    .el-form-item__content {
      width: 100%;
    }
    
    .el-form-item__label {
      color: #333 !important;
      font-weight: 500;
    }
  }
}

.unit {
  margin-left: 8px;
  color: #666;
  font-size: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  .compact-form {
    .el-form-item__label {
      width: 60px !important;
      font-size: 12px;
      color: #333 !important;
      font-weight: 500;
    }
    
    .el-input__inner {
      color: #333 !important;
    }
    
    .el-radio__label {
      color: #333 !important;
    }
  }
  
  .items-config-card {
    .item-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
      
      .item-actions {
        width: 100%;
        justify-content: flex-end;
      }
    }
    
    .full-width-item {
      .el-form-item__label {
        width: 60px !important;
        font-size: 12px;
        color: #333 !important;
        font-weight: 500;
      }
    }
  }
}

@media (max-width: 480px) {
  .compact-form {
    .el-form-item__label {
      width: 50px !important;
      color: #333 !important;
      font-weight: 500;
    }
    
    .el-input__inner {
      color: #333 !important;
    }
    
    .el-radio__label {
      color: #333 !important;
    }
  }
  
  .items-config-card {
    .item-config {
      padding: 8px;
    }
    
    .item-actions {
      .el-button {
        padding: 2px 6px;
        font-size: 11px;
      }
    }
    
    .full-width-item {
      .el-form-item__label {
        width: 50px !important;
        font-size: 11px;
        color: #333 !important;
        font-weight: 500;
      }
    }
  }
}

// 弹框层级
:deep(.el-dialog__wrapper) {
  z-index: 10000;
}
</style>
